<template>
  <view class="create-container">
    <uni-card title="创建新项目" :is-shadow="false">
      <view class="form-section">
        <uni-forms ref="form" :model="projectForm" :rules="rules">
          <!-- 项目名称 -->
          <uni-forms-item label="项目名称" name="projectName">
            <uni-easyinput v-model="projectForm.projectName" placeholder="请输入项目名称" />
          </uni-forms-item>        
          <!-- 客户选择 -->
          <uni-forms-item label="选择客户" name="customerId">
            <uni-data-select
              v-model="projectForm.companyId"
              :localdata="customers"
              @change="onCustomerChange"
              label="text"
              value="value"
              placeholder="请选择客户"
            />
          </uni-forms-item>
          <uni-forms-item label="备注" name="remark" class="form-item">
           <uni-easyinput v-model="projectForm.remark" type="textarea" placeholder="请输入备注信息" />
          </uni-forms-item>
          <!-- 产品列表 -->
          <uni-forms-item label="产品列表">
            <view class="product-list">
              <view v-for="(product, index) in projectForm.projectCargoList" :key="index" class="product-item">
                <uni-forms-item :label="'产品' + (index + 1)" :name="['products', index, 'name']">
                  <uni-easyinput v-model="product.cargoName" placeholder="请输入产品名称" />
                </uni-forms-item>
                <uni-forms-item :label="'数量' + (index + 1)" :name="['products', index, 'quantity']">
                  <uni-number-box v-model="product.cargoNum" :min="1" :max="9999" />
                </uni-forms-item>
                <button size="mini" type="default" @click="removeProduct(index)" class="remove-btn">删除</button>
              </view>
            </view>
            <button type="primary" size="mini" @click="addProduct" class="add-btn">添加产品</button>
          </uni-forms-item>
        </uni-forms>
      </view>
      
      <!-- 提交按钮 -->
      <view class="form-actions">
        <button type="primary" @click="submitForm" class="save-btn">保存项目</button>
        <button type="default" @click="cancelForm">取消</button>
      </view>
    </uni-card>
  </view>
</template>

<script>
import { addProject } from "@/api/mes/project"
import { listCompany} from "@/api/mes/company"
export default {
  data() {
    return {
      customers: [
      ],
      projectForm: {
        projectName: '',
        companyId: '',
        projectCargoList: [
          { cargoName: '', cargoNum: 1 }
        ]
      },
      rules: {
        name: {
          rules: [{ required: true, errorMessage: '请输入项目名称' }]
        },
        customerId: {
          rules: [{ required: true, errorMessage: '请选择客户' }]
        },
        products: {
          rules: [{ required: true, errorMessage: '请至少添加一个产品' }]
        }
      }
    }
  },
  onLoad() {
    this.getCostomerSelect();
  },
  methods: {
    onCustomerChange(value) {
      const selectedCustomer = this.customers.find(item => item.value === value);
      if (selectedCustomer) {
        this.projectForm.customerId = selectedCustomer.value;
        // this.projectForm.customerName = selectedCustomer.text;
      }
    },
    addProduct() {
      this.projectForm.projectCargoList.push({ cargoName: '', cargoNum: 1 })
    },
    removeProduct(index) {
      if (this.projectForm.projectCargoList.length > 1) {
        this.projectForm.projectCargoList.splice(index, 1)
      } else {
        uni.showToast({
          title: '至少需要一个产品',
          icon: 'none'
        })
      }
    },
    submitForm() {
      this.$refs.form.validate().then(res => {

        
        addProject(this.projectForm).then(response => {
          uni.showToast({
            title: '添加成功',
            icon: 'success'
          });
          // 延迟后直接跳转到列表页，不再使用navigateBack
          setTimeout(() => {
            // 使用navigateBack返回上一页
            uni.navigateBack({
              delta: 1,
              success: function() {
                // 获取当前页面栈
                const pages = getCurrentPages();
                // 获取上一页实例
                const prevPage = pages[pages.length - 1];
                // 调用上一页的刷新方法
              }
            });
          }, 100);
        }).catch(err => {
          uni.showToast({
            title: '添加失败',
            icon: 'none'
          });
        });
      }).catch(err => {
        console.log('表单错误：', err);
      });
    },
    cancelForm() {
      uni.navigateBack()
    },
    getCostomerSelect() {
      listCompany().then(response => {
        this.customers = response.rows.map(customers => ({
            value: customers.companyId.toString(),
            text: customers.companyName
          }));
      });
    }
  }
}

</script>

<style lang="scss" scoped>
.create-container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
  
  .form-section {
    margin-bottom: 30rpx;
  }
  
  :deep(.uni-forms-item) {
    margin-bottom: 22rpx;
    
    .uni-forms-item__label {
      font-size: 28rpx;
      color: #606266;
    }
  }
  
  :deep(.uni-easyinput__content),
  :deep(.uni-data-select) {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    
    &:hover {
      border-color: #409eff;
    }
  }
  
  .product-list {
    .product-item {
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 16rpx;
      margin-bottom: 16rpx;
      
      :deep(.uni-forms-item__content) {
        display: flex;
        align-items: center;
      }
      
      .remove-btn {
        margin-left: 16rpx;
      }
    }
  }
  
  .add-btn {
    margin-top: 16rpx;
  }
  
  .form-actions {
    display: flex;
    justify-content: space-between;
    
    button {
      width: 45%;
    }
    
    .save-btn {
      background-color: #007AFF;
    }
  }
}
.form-item {
      margin-bottom: 24rpx;
      
      :deep(.uni-forms-item__label) {
        font-size: 28rpx;
        color: #333;
        padding: 0 12rpx;
      }
      
      :deep(.uni-easyinput__content) {
        min-height: 72rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        input {
          font-size: 28rpx;
        }
      }
      
      :deep(.uni-data-select) {
        .uni-select--mask {
          background-color: #f8f8f8;
          border-radius: 8rpx;
        }
        
        .uni-select__input-text {
          font-size: 28rpx;
        }
      }
    }
</style>
